
#include "TcpServer.h"

#include <QDebug>

TcpServer::TcpServer(QObject * parent):QTcpServer(parent)
{
}
TcpServer::~TcpServer()
{
    while(!clientList.isEmpty())
    {
        clientList.takeFirst()->deleteLater();//delete
    }
    close();
}

void TcpServer::Remove(TcpSocket* pTcpSocket)
{
    if(pTcpSocket != NULL)
    {
        if(clientList.removeOne(pTcpSocket))
            pTcpSocket->deleteLater();
    }
}

TcpSocket* TcpServer::createTcpSocket()
{
    return new TcpSocket(this);
}

void TcpServer::incomingConnection(qintptr handle)
{
    TcpSocket * socket = createTcpSocket();
    clientList.append(socket);

    if (!socket->setSocketDescriptor(handle))//将它的套接宇描述符设置成提供给我们的数字。
    {
        //qDebug()<<(int)socket->error();
        qDebug()<<socket->errorString();
        return;
    }



    connect(socket, SIGNAL(s_hostFound(TcpSocket *)),
              this, SIGNAL(hostFound(TcpSocket *)));
    //连接函数
    //connect(socket, SIGNAL(s_connected(TcpSocket *)),
    //          this, SIGNAL(connected(TcpSocket *)));
    //断开
    connect(socket, SIGNAL(s_disconnected(TcpSocket *)),
              this, SIGNAL(disconnected(TcpSocket *)));

    connect(socket, SIGNAL(s_stateChanged(qint16,TcpSocket*)),
              this, SIGNAL(stateChanged(qint16, TcpSocket *)));
    //错误函数
    connect(socket, SIGNAL(s_error(qint16, TcpSocket *)),
              this, SIGNAL(error(qint16, TcpSocket *)));
    //有数据
    connect(socket, SIGNAL(s_readyRead(TcpSocket *)),
              this, SIGNAL(readyRead(TcpSocket *)));
    connect(socket, SIGNAL(s_bytesWritten(qint64, TcpSocket *)),
              this, SIGNAL(bytesWritten(qint64, TcpSocket *)));
    connect(socket, SIGNAL(s_aboutToClose(TcpSocket *)),
              this, SIGNAL(aboutToClose(TcpSocket *)));
    connect(socket, SIGNAL(s_readChannelFinished(TcpSocket *)),
              this, SIGNAL(readChannelFinished(TcpSocket *)));

    emit connected(socket);
}
